/**$6
 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 * main(voi) di test per il driver
 * definisce prototipi OSA, CONFIG, e poco altro 
 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 */

/* System Include */
#include <string.h>

/* Local Include */
#include "Generic.h"
#include "Config.h"
#include "osa.h"
#include "service/osa_bsem.h"
#include "service/osa_dtimer.h"
#include "rs485.h"
#include "init.h"
#if defined __18CXX
	#include "heap.h"
	#include "alloc.h"
#endif
#include "delay.h"
/* OSA PROTOTIPE */
void	Drv_Rs485(void);
void	Governor(void);
void	task_keyboard(void);

/*
 * P R O T O T Y P E S ;
 * Global variables
 */
static const char	txt[] = "123456789";
static TxPacket		*tx_commpack;
#if defined(__C30__)

/* Durante il debug FAST RC + PLL */
_CONFIG2(IESO_OFF & FNOSC_FRCPLL  & FCKSM_CSDCMD & OSCIOFNC_ON & POSCMOD_HS & I2C1SEL_PRI)
_CONFIG1(JTAGEN_OFF &GCP_OFF &GWRP_OFF &COE_OFF &ICS_PGx1 &FWDTEN_OFF &WINDIS_OFF);
#endif

/**
 =======================================================================================================================
 * main(void) di test
 =======================================================================================================================
 */
void main(void)
{
	/*~~~~~~~~~~*/
	WORD	cAddr; /* nostro indirizzo*/
	/*~~~~~~~~~~*/

#if defined(__OSAMCC30__)
	init();
#elif defined(__18CXX)
	init();
	heapinit();
#endif

	/* OSA Init */
	OS_Init();
	OS_CreateTask(4, Drv_Rs485);
	OS_CreateTask(4, Governor);
	OS_CreateTask(4, task_keyboard);
	
	/*
	 * OS_CreateTask(4, task_keyboard);
	 */
	tx_commpack = calloc(1, sizeof(TxPacket));
	cAddr = 0x0101;
	Rs485Initialise(cAddr);
	OS_Run();
	free(tx_commpack);
}

/**
 =======================================================================================================================
 *	Task Governor
 * 	Gestisce le interazioni tra task e task /esterno
 =======================================================================================================================
 */
void Governor(void)
{
	OS_Queue_Create(DRV_rs485_qmsg_rx, DRV_rs485_msg_q_rx, RS485_SIZEOF_MSGQ);
	OS_Queue_Create(DRV_rs485_qmsg_tx, DRV_rs485_msg_q_tx, RS485_SIZEOF_MSGQ);

	/* FIXME define... */
	OS_SQueue_Create(DRV_rs485_q_char, DRV_rs485_smsg_q_char, RS485_SIZEOF_CBUF);
	while (1)
	{
		OS_Flag_Wait_1x(F_Button,0xff);
		
			OS_SetFlag(Rs485Flag, SER_TX);
			tx_commpack->cStart = 0x02; /* FIXME ererdt m */
			tx_commpack->cCommand = 0xfe;
			tx_commpack->cLenExpected = 9;
			tx_commpack->cNetAddr = 0x0102;
			strcpy(tx_commpack->c485Buf, txt);
			OS_SendQMsg(DRV_rs485_qmsg_tx, (char *) tx_commpack);
			OS_ResetBSem(BS_BUTTON_1_REL);
		

		OS_Yield();
	}
}
